use fluviox_connector_framework::{
    registry::{ConnectorRegistry, get_global_registry},
    traits::{ConnectorFactory, ConnectorConfig, SourceConnector, DestinationConnector},
    sources::{HttpSourceConfig, DatabaseSourceConfig, FileSourceConfig},
    destinations::{DatabaseDestinationConfig, FileDestinationConfig, HttpDestinationConfig},
    config::{ConfigValidator, ConfigTemplateGenerator},
};
use serde_json::json;

#[test]
fn test_connector_registry() {
    let registry = ConnectorRegistry::new();
    
    // 测试支持的连接器列表
    let sources = registry.list_sources();
    assert!(sources.contains(&"http".to_string()));
    assert!(sources.contains(&"database".to_string()));
    assert!(sources.contains(&"file".to_string()));
    
    let destinations = registry.list_destinations();
    assert!(destinations.contains(&"database".to_string()));
    assert!(destinations.contains(&"file".to_string()));
    assert!(destinations.contains(&"http".to_string()));
    
    println!("✅ 连接器注册表测试通过");
}

#[test]
fn test_connector_creation() {
    let registry = ConnectorRegistry::new();

    // 测试创建数据源连接器
    let http_source = registry.create_http_source();
    assert_eq!(http_source.name(), "http-source");

    let db_source = registry.create_database_source();
    assert_eq!(db_source.name(), "database-source");

    let file_source = registry.create_file_source();
    assert_eq!(file_source.name(), "file-source");

    // 测试创建目标连接器
    let db_destination = registry.create_database_destination();
    assert_eq!(db_destination.name(), "database-destination");

    let file_destination = registry.create_file_destination();
    assert_eq!(file_destination.name(), "file-destination");

    let http_destination = registry.create_http_destination();
    assert_eq!(http_destination.name(), "http-destination");

    // 测试工厂方法
    let factory_source = registry.create_source("http");
    assert!(factory_source.is_ok());

    let unknown_source = registry.create_source("unknown");
    assert!(unknown_source.is_err());

    println!("✅ 连接器创建测试通过");
}

#[test]
fn test_global_registry() {
    let registry = get_global_registry();
    
    let sources = registry.list_sources();
    assert!(!sources.is_empty());
    
    let destinations = registry.list_destinations();
    assert!(!destinations.is_empty());
    
    println!("✅ 全局注册表测试通过");
}

#[test]
fn test_connector_metadata() {
    let registry = ConnectorRegistry::new();
    
    let source_metadata = registry.supported_sources();
    assert!(!source_metadata.is_empty());
    
    let destination_metadata = registry.supported_destinations();
    assert!(!destination_metadata.is_empty());
    
    // 验证HTTP连接器元数据
    let http_meta = source_metadata.iter()
        .find(|m| m.name == "http")
        .expect("应该找到HTTP连接器元数据");
    
    assert_eq!(http_meta.version, "1.0.0");
    assert!(!http_meta.description.is_empty());
    assert!(!http_meta.configuration_schema.is_null());
    
    println!("✅ 连接器元数据测试通过");
}

#[test]
fn test_http_source_config() {
    // 测试有效配置
    let valid_config = HttpSourceConfig {
        url: "https://api.example.com/data".to_string(),
        method: "GET".to_string(),
        headers: std::collections::HashMap::new(),
        body: None,
        poll_interval: 60,
        auth: None,
        pagination: None,
        data_path: None,
        timeout: Some(30),
    };
    
    assert!(valid_config.validate().is_ok());
    
    // 测试配置序列化
    let json_value = valid_config.to_json().unwrap();
    assert!(json_value.is_object());
    
    // 测试配置反序列化
    let restored_config = HttpSourceConfig::from_json(json_value).unwrap();
    assert_eq!(restored_config.url, valid_config.url);
    
    // 测试无效配置
    let invalid_config = HttpSourceConfig {
        url: "".to_string(),
        method: "GET".to_string(),
        headers: std::collections::HashMap::new(),
        body: None,
        poll_interval: 60,
        auth: None,
        pagination: None,
        data_path: None,
        timeout: Some(30),
    };
    
    assert!(invalid_config.validate().is_err());
    
    println!("✅ HTTP数据源配置测试通过");
}

#[test]
fn test_database_source_config() {
    let valid_config = DatabaseSourceConfig {
        connection_url: "postgresql://user:pass@localhost:5432/db".to_string(),
        database_type: fluviox_connector_framework::sources::DatabaseType::PostgreSQL,
        query: "SELECT * FROM users".to_string(),
        incremental: None,
        poll_interval: 300,
        batch_size: 1000,
        pool_config: None,
    };
    
    assert!(valid_config.validate().is_ok());
    
    // 测试无效配置
    let invalid_config = DatabaseSourceConfig {
        connection_url: "".to_string(),
        database_type: fluviox_connector_framework::sources::DatabaseType::PostgreSQL,
        query: "SELECT * FROM users".to_string(),
        incremental: None,
        poll_interval: 300,
        batch_size: 1000,
        pool_config: None,
    };
    
    assert!(invalid_config.validate().is_err());
    
    println!("✅ 数据库数据源配置测试通过");
}

#[test]
fn test_file_source_config() {
    let valid_config = FileSourceConfig {
        path: "/path/to/files".to_string(),
        format: fluviox_connector_framework::sources::FileFormat::JsonLines,
        watch_mode: true,
        poll_interval: 60,
        encoding: "utf-8".to_string(),
        csv_config: None,
        json_config: None,
        file_pattern: Some("*.json".to_string()),
        recursive: false,
    };
    
    assert!(valid_config.validate().is_ok());
    
    println!("✅ 文件数据源配置测试通过");
}

#[test]
fn test_database_destination_config() {
    let valid_config = DatabaseDestinationConfig {
        connection_url: "postgresql://user:pass@localhost:5432/db".to_string(),
        table_name: "target_table".to_string(),
        write_mode: fluviox_connector_framework::destinations::WriteMode::Insert,
        batch_size: 1000,
        field_mapping: None,
        auto_create_table: false,
        primary_key: None,
    };
    
    assert!(valid_config.validate().is_ok());
    
    println!("✅ 数据库目标配置测试通过");
}

#[test]
fn test_file_destination_config() {
    use fluviox_connector_framework::destinations::{FileOutputFormat, FileWriteMode};

    let valid_config = FileDestinationConfig {
        path: "/tmp/output.json".to_string(),
        format: FileOutputFormat::JsonLines,
        write_mode: FileWriteMode::Append,
        append: true,
        batch_size: 1000,
        encoding: "utf-8".to_string(),
        create_dirs: true,
        rotation: None,
    };

    assert!(valid_config.validate().is_ok());

    // 测试无效配置
    let invalid_config = FileDestinationConfig {
        path: "".to_string(),
        format: FileOutputFormat::JsonLines,
        write_mode: FileWriteMode::Append,
        append: true,
        batch_size: 0,
        encoding: "utf-8".to_string(),
        create_dirs: true,
        rotation: None,
    };

    assert!(invalid_config.validate().is_err());

    println!("✅ 文件目标配置测试通过");
}

#[test]
fn test_http_destination_config() {
    use fluviox_connector_framework::destinations::{HttpDataFormat};

    let valid_config = HttpDestinationConfig {
        url: "https://api.example.com/webhook".to_string(),
        method: "POST".to_string(),
        headers: std::collections::HashMap::new(),
        auth: None,
        batch_size: 100,
        timeout: Some(30),
        retry: None,
        format: HttpDataFormat::Json,
        batch_mode: true,
    };

    assert!(valid_config.validate().is_ok());

    // 测试无效配置
    let invalid_config = HttpDestinationConfig {
        url: "invalid-url".to_string(),
        method: "INVALID".to_string(),
        headers: std::collections::HashMap::new(),
        auth: None,
        batch_size: 0,
        timeout: Some(30),
        retry: None,
        format: HttpDataFormat::Json,
        batch_mode: true,
    };

    assert!(invalid_config.validate().is_err());

    println!("✅ HTTP目标配置测试通过");
}

#[test]
fn test_config_validator() {
    // 测试HTTP配置验证
    let valid_http_config = json!({
        "url": "https://api.example.com/data",
        "method": "GET",
        "poll_interval": 60
    });
    
    assert!(ConfigValidator::validate_config("http", &valid_http_config).is_ok());
    
    let invalid_http_config = json!({
        "url": "",
        "method": "INVALID"
    });
    
    assert!(ConfigValidator::validate_config("http", &invalid_http_config).is_err());
    
    // 测试数据库配置验证
    let valid_db_config = json!({
        "connection_url": "postgresql://localhost:5432/db",
        "query": "SELECT * FROM table"
    });
    
    assert!(ConfigValidator::validate_config("database", &valid_db_config).is_ok());
    
    println!("✅ 配置验证器测试通过");
}

#[test]
fn test_config_template_generator() {
    // 测试HTTP模板生成
    let http_template = ConfigTemplateGenerator::generate_template("http");
    assert!(http_template.is_object());
    assert!(http_template.get("url").is_some());
    
    // 测试数据库模板生成
    let db_template = ConfigTemplateGenerator::generate_template("database");
    assert!(db_template.is_object());
    assert!(db_template.get("connection_url").is_some());
    
    // 测试文件模板生成
    let file_template = ConfigTemplateGenerator::generate_template("file");
    assert!(file_template.is_object());
    assert!(file_template.get("path").is_some());
    
    println!("✅ 配置模板生成器测试通过");
}

#[tokio::test]
async fn test_connector_lifecycle() {
    let registry = ConnectorRegistry::new();

    // 创建HTTP数据源连接器
    let mut http_source = registry.create_http_source();

    // 测试连接器基本信息
    assert_eq!(http_source.name(), "http-source");
    assert_eq!(http_source.version(), "1.0.0");
    assert!(!http_source.description().is_empty());

    // 测试初始状态
    assert!(matches!(http_source.status(), fluviox_connector_framework::traits::ConnectorStatus::Uninitialized));

    // 创建配置
    let config = HttpSourceConfig {
        url: "https://httpbin.org/json".to_string(),
        method: "GET".to_string(),
        headers: std::collections::HashMap::new(),
        body: None,
        poll_interval: 60,
        auth: None,
        pagination: None,
        data_path: None,
        timeout: Some(30),
    };

    // 初始化连接器
    let init_result = http_source.initialize(config).await;
    assert!(init_result.is_ok());

    // 测试连接（这可能会失败，因为需要网络连接）
    let test_result = http_source.test_connection().await;
    // 不强制要求测试成功，因为可能没有网络连接
    println!("连接测试结果: {:?}", test_result);

    // 启动连接器
    let start_result = http_source.start().await;
    assert!(start_result.is_ok());

    // 停止连接器
    let stop_result = http_source.stop().await;
    assert!(stop_result.is_ok());

    println!("✅ 连接器生命周期测试通过");
}
